﻿
import shlex
import string
import sys
import argparse
import fnmatch

from karmadbg.dbgcore.util import showtraceback

def registerUiCommand(name, desc, fn):
    uicmdLst[name] = (name, fn, desc)

def getUiCommand(name):

    cmd = uicmdLst.get(name)
    if cmd:
        return cmd[1]
    return None

def runUiCommand(cmdLine):

    try:

        if not cmdLine:
            return False

        shl = shlex.shlex(cmdLine, posix=True)
        shl.escape = []
        shl.wordchars = string.digits + string.ascii_letters + r"!#$%&()*+,-./:;<=>?@[\]^_`{|}~"
        vars =list(shl)

        if  vars[0][0] != '.':
            return False

        uicmd = getUiCommand( vars[0][1:] )
        if not uicmd:
            return False

        vars = vars[1:]

        ret = uicmd(*vars)

    except Exception as e:
        print showtraceback(sys.exc_info())
        print "UI command exception!!!"

    return True


def uiCommand( *args):

    class ArgParser(argparse.ArgumentParser):

        def error(self, message):
            sys.stdout.write('error: %s\n' % message)
            self.print_help()
            self.exit()

        def parse_args(self, *args):
            try:
               return super(ArgParser, self).parse_args(*args)
            except SystemExit:
                return None

    def uiCommandList(args):
        print
        for cmd in sorted( filter( lambda x: fnmatch.fnmatch( x[0], args.mask), uicmdLst.values()), key = lambda x: x[0] ):
            print cmd[0]
            print "\t", cmd[2]
            print
             
    argparser = ArgParser(prog=".uicmd")
    subparser = argparser.add_subparsers(help='sub-command help')
    listparser = subparser.add_parser('list')
    listparser.add_argument( 'mask', nargs='?', default='*', help='command name mask')
    listparser.set_defaults(func=uiCommandList)

    args = argparser.parse_args(args)
    if args: args.func(args)

uicmdLst = {}

registerUiCommand("uicmd", "UI command", uiCommand);




